﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XingFuStudio.Pioneer.Net;
using XingFuStudio.Pioneer.IO;
using XingFuStudio.Pioneer.Entity;
using XingFuStudio.Pioneer.Container.Interface.Event;
using FluorineFx.IO;
using XingFuStudio.Pioneer.BusinessLogic;
using System.IO;
using XingFuStudio.Pioneer.Applications.City.Operation;
using XingFuStudio.Pioneer.Applications.City.Config;
using XingFuStudio.Pioneer.Applications.City.Entity;
using XingFuStudio.Pioneer.Applications.City.Element;

namespace XingFuStudio.Pioneer.Applications.City {
    /// <summary>
    /// 开心城市管理类
    /// </summary>
    public class CityManager {
        #region 事件

        /// <summary>
        /// 打印日志事件
        /// </summary>
        public event EventHandler<LogEventArgs> PrintLog = null;
        /// <summary>
        /// 出错事件
        /// </summary>
        public event EventHandler<XingFuStudio.Pioneer.Container.Interface.Event.ErrorEventArgs> Error = null;

        /// <summary>
        /// 执行打印日志事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="isNewLine"></param>
        /// <param name="formate"></param>
        /// <param name="args"></param>
        protected void DoPrintLog(bool isNewLine, string format, params object[] args) {
            if (this.PrintLog != null) {
                this.PrintLog(this, new LogEventArgs() {
                    IsNewLing = isNewLine, LogMessage = String.Format(format, args)
                });
            }
        }

        /// <summary>
        /// 执行出错事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="ex"></param>
        protected void DoError(Exception ex) {
            if (this.Error != null) {
                this.Error(this, new XingFuStudio.Pioneer.Container.Interface.Event.ErrorEventArgs() {
                    Exception = ex
                });
            }
        }

        #endregion

        /// <summary>
        /// 应用对应开心网编码
        /// </summary>
        private readonly int AppCode = 1226;
        /// <summary>
        /// Http请求管理类对象
        /// </summary>
        private HttpManager httpManager = null;
        /// <summary>
        /// 帐户实体对象
        /// </summary>
        private AccountInfo account = null;
        /// <summary>
        /// 我的城市信息
        /// </summary>
        private CityInfo myCity = new CityInfo();

        /// <summary>
        /// 获取或设置帐户
        /// </summary>
        public AccountInfo Account {
            get {
                return account;
            }
            set {
                account = value;
            }
        }

        /// <summary>
        /// 获取或设置Http请求管理类对象
        /// </summary>
        public HttpManager HttpManager {
            get {
                return httpManager;
            }
            set {
                httpManager = value;
            }
        }

        /// <summary>
        /// 创建一个<see cref="CityManager"/>实例
        /// </summary>
        public CityManager() {
            
        }

        /// <summary>
        /// 创建一个<see cref="CityManager"/>实例
        /// </summary>
        /// <param name="httpManager"></param>
        /// <param name="account"></param>
        public CityManager(HttpManager httpManager, AccountInfo account) {
            this.ChangeAccount(httpManager, account);
        }

        /// <summary>
        /// 初始化帐户信息
        /// </summary>
        public void ChangeAccount(HttpManager httpManager, AccountInfo account) {
            //初始化开心网Http请求处理类对象
            this.httpManager = httpManager;
            //初始化登录帐户
            this.account = account;
        }

        /// <summary>
        /// 运行管理
        /// </summary>
        public void Run() {
            //初始化城市信息对象
            this.myCity = new CityInfo();

            //初始化公共操作对象
            OPCommon opCommon = new OPCommon(this.httpManager, this.account, this.myCity);

            //获取帐户验证码
            string verifyCode = this.GetVerifyCode();
            myCity.VerifyCode = verifyCode;
            //获取登录ID
            string loginId = opCommon.GetLoginId();
            myCity.LoginId = loginId;

            //打印日志
            this.DoPrintLog(true, "获取城市信息...");
            //获取城市信息
            this.myCity = opCommon.GetCityInfo(this.Account);
            //赋值城市属性
            myCity.VerifyCode = verifyCode;
            myCity.LoginId = loginId;
            //由于City对象变更，需要重新初始化共公操作对象
            opCommon = new OPCommon(this.httpManager, this.account, this.myCity);

            //打印日志
            this.DoPrintLog(true, "我的城市 等级:{3} 现金:{0} 货物:{4} 体力:{1} 经验:{2}/{5}", 
                myCity.Cash, myCity.Energy, myCity.Exp, myCity.Level, myCity.Goods, myCity.NextLevelExp);

            //牙
            //var temp1 = this.myCity.Elements.Where(s => s.ElementId == 127);
            //天文
            var temp1 = this.myCity.Elements.Where(s => s.OrderId == "2187298879");
            //消防
            var temp2 = this.myCity.Elements.Where(s => s.OrderId == "2193503624");
            //机器人
            var temp3 = this.myCity.Elements.Where(s => s.OrderId == "2167558135");

            //获取当前帐户的配置文件
            List<UserConfigSection> configs = new UserConfig(account).GetUserConfigs();

            //#region 测试用的代码

            //判断是否读到配置，为了测试，临时加入的代码
            if (configs.Count == 0) {
                UserConfigSection section = new UserConfigSection();
                section.OPName = "Friend";
                section.IsRun = true;
                new UserConfig(this.account).ModifyConfig(section);
                section = new UserConfigSection();
                section.OPName = "Business";
                section.IsRun = true;
                section.ConfigItems.Add("AutoHarvest", true);
                section.ConfigItems.Add("AutoReceive", true);
                section.ConfigItems.Add("AutoDeliver", true);
                new UserConfig(this.account).ModifyConfig(section);
                section = new UserConfigSection();
                section.OPName = "Franchise";
                section.IsRun = true;
                new UserConfig(this.account).ModifyConfig(section);
                section = new UserConfigSection();
                section.OPName = "Residence";
                section.IsRun = true;
                section.ConfigItems.Add("AutoHarvest", true);
                section.ConfigItems.Add("AutoUpLevel", true);
                new UserConfig(this.account).ModifyConfig(section);
                section = new UserConfigSection();
                section.OPName = "Agriculture";
                section.IsRun = true;
                section.ConfigItems.Add("AutoHarvest", true);
                section.ConfigItems.Add("AutoPlow", true);
                section.ConfigItems.Add("AutoSow", true);
                section.ConfigItems.Add("SowFarmId", 2);
                new UserConfig(this.account).ModifyConfig(section);
                section = new UserConfigSection();
                section.OPName = "Ship";
                section.IsRun = true;
                section.ConfigItems.Add("AutoHarvest", true);
                section.ConfigItems.Add("AutoStart", true);
                section.ConfigItems.Add("SellItemId", 2041);
                new UserConfig(this.account).ModifyConfig(section);
                section = new UserConfigSection();
                section.OPName = "Gift";
                section.IsRun = true;
                new UserConfig(this.account).ModifyConfig(section);
                section = new UserConfigSection();
                section.OPName = "Oilwell";
                section.IsRun = true;
                section.ConfigItems.Add("AutoHarvest", true);
                section.ConfigItems.Add("AutoProduct", true);
                section.ConfigItems.Add("ProductionId", 1);
                new UserConfig(this.account).ModifyConfig(section);
                section = new UserConfigSection();
                section.OPName = "Factory";
                section.IsRun = true;
                section.ConfigItems.Add("AutoHarvest", true);
                section.ConfigItems.Add("AutoProduct", true);
                section.ConfigItems.Add("ProductionId", 22);
                new UserConfig(this.account).ModifyConfig(section);
                section = new UserConfigSection();
                section.OPName = "Infrastructure";
                section.IsRun = true;
                section.ConfigItems.Add("AutoHarvest", true);
                section.ConfigItems.Add("AutoUpLevel", true);
                new UserConfig(this.account).ModifyConfig(section);
                section = new UserConfigSection();
                section.OPName = "Temporary";
                section.IsRun = true;
                new UserConfig(this.account).ModifyConfig(section);
                section = new UserConfigSection();
                section.OPName = "Train";
                section.IsRun = true;
                section.ConfigItems.Add("AutoDeal", true);
                section.ConfigItems.Add("AutoAccept", true);
                section.ConfigItems.Add("AutoSendOut", true);
                section.ConfigItems.Add("SendOutOrderId", 4);
                new UserConfig(this.account).ModifyConfig(section);
                section = new UserConfigSection();
                section.OPName = "Execute";
                section.IsRun = true;
                section.ConfigItems.Add("AutoAid", true);
                section.ConfigItems.Add("AutoArrest", true);
                new UserConfig(this.account).ModifyConfig(section);
                section = new UserConfigSection();
                section.OPName = "Gray";
                section.IsRun = true;
                section.ConfigItems.Add("AutoHarvest", true);
                section.ConfigItems.Add("AutoDeliver", true);
                section.ConfigItems.Add("HavestTime", 720);
                new UserConfig(this.account).ModifyConfig(section);

                configs = new UserConfig(account).GetUserConfigs();
            }

            //#endregion

            //遍历各模块的配置节
            foreach (UserConfigSection config in configs) {
                //判断用户配置中当前配置操作是否执行
                if (config.IsRun) {
                    //初始化当前操作
                    OPBase operate = OPFactory.CreateOperate(config, httpManager, account, myCity);

                    if (operate != null) {
                        operate.PrintLog += new EventHandler<LogEventArgs>(Operate_PrintLog);
                        operate.Error += new EventHandler<XingFuStudio.Pioneer.Container.Interface.Event.ErrorEventArgs>(Operate_Error);

                        //执行操作
                        operate.Operate();
                    }
                }
            }
        }

        /// <summary>
        /// 操作执行过程出错事件方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Operate_Error(object sender, Container.Interface.Event.ErrorEventArgs e) {
            this.DoError(e.Exception);
        }

        /// <summary>
        /// 操作执行过程日志事件方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Operate_PrintLog(object sender, LogEventArgs e) {
            this.DoPrintLog(e.IsNewLing, e.LogMessage);
        }

        /// <summary>
        /// 获取帐户验证编码
        /// </summary>
        /// <returns></returns>
        public string GetVerifyCode() {
            //访问主页
            string content = LoginManager.GetAppHomePage(this.httpManager, this.AppCode);
            //获取当前用户验证码
            string verifyCode = content.GetMidString("verify=", "'");
            //返回当前用户验证码
            return verifyCode;
        }
    }
}
